package org.linlinjava.litemall.wx.web;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallGoodsProductService;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.Order2Service;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxOrderService;
import org.linlinjava.litemall.wx.vo.OrderDTO;
import org.linlinjava.litemall.wx.vo.ProductItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信小程序订单相关接口的控制器
 * 处理订单的创建、查询、支付等操作
 */
@RestController
@RequestMapping("/wx/order")
@Validated
public class WxOrderController {
    private final Log logger = LogFactory.getLog(WxOrderController.class);

    @Autowired
    private WxOrderService wxOrderService;  // 订单业务逻辑服务
    
    @Autowired
    private Order2Service order2Service;    // 订单基础服务
    
    @Autowired
    private LitemallGoodsProductService goodsProductService;  // 商品规格服务
    
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;     // 订单商品关联服务

    // PDF文件保存路径
    private final String pdfSavePath = "D:\\pdf";

    /**
     * 创建新订单
     * 处理流程:
     * 1. 解析订单数据
     * 2. 检查库存
     * 3. 创建订单记录
     * 4. 更新库存
     * 
     * @param orderData JSON格式的订单数据,包含:
     *                  - contract: 合同信息
     *                  - payment: 支付信息
     *                  - companies: 买卖方公司信息
     *                  - products: 商品信息
     *                  - time: 订单时间信息
     * @return 成功返回ResponseUtil.ok(),失败返回对应错误信息
     */
    @PostMapping("insert")
    public Object insert(@RequestBody JSONObject orderData) {
        try {
            // 1. 解析订单基本信息和商品信息
            Order2 order2 = parseOrderFromJson(orderData);
            List<LitemallOrderGoods> orderGoodsList = parseOrderGoodsWithoutOrderId(orderData);
            
            // 2. 检查商品库存是否充足
            if (!checkProductStock(orderGoodsList)) {
                return ResponseUtil.fail(403, "部分商品库存不足");
            }
            
            // 3. 创建订单并保存订单商品信息
            order2Service.insert(order2);  // 先保存订单主表信息
            saveOrderGoods(orderGoodsList, Math.toIntExact(order2.getId()));  // 再保存订单商品关联信息
            
            // 4. 更新商品库存数量
            updateProductStock(orderGoodsList);  // 扣减库存
            
            return ResponseUtil.ok();
        } catch (Exception e) {
            String errorMessage = e.getMessage().toLowerCase();
            return handleOrderError(e, errorMessage);
        }
    }

    /**
     * 解析订单商品信息
     * 从JSON数据中提取商品列表,并转换为订单商品对象
     * 
     * @param orderData JSON格式的订单数据
     * @return 订单商品对象列表
     * @throws Exception 当商品不存在或数据格式错误时抛出异常
     */
    private List<LitemallOrderGoods> parseOrderGoodsWithoutOrderId(JSONObject orderData) throws Exception {
        // 获取商品数组
        JSONArray products = orderData.getJSONArray("products");
        List<LitemallOrderGoods> orderGoodsList = new ArrayList<>(products.size());
        LocalDateTime now = parseOrderTime(orderData);

        // 遍历处理每个商品
        for (int i = 0; i < products.size(); i++) {
            JSONObject product = products.getJSONObject(i);
            JSONObject properties = product.getJSONObject("properties");

            // 查询商品是否存在及其规格信息
            List<LitemallGoodsProduct> goodsProducts = goodsProductService.queryByGid(properties.getInteger("id"));
            if (goodsProducts.isEmpty()) {
                throw new IllegalArgumentException("商品不存在");
            }

            // 构建订单商品对象,设置商品的基本信息、价格、数量等
            LitemallOrderGoods goods = LitemallOrderGoods.builder()
                    .goodsId(properties.getInteger("id"))          // 商品ID
                    .goodsName(product.getString("name"))          // 商品名称
                    .goodsSn(properties.getString("goodsSn"))      // 商品编号
                    .productId(goodsProducts.get(0).getId())       // 商品规格ID
                    .number(product.getShort("quantity"))          // 购买数量
                    .price(properties.getBigDecimal("counterPrice"))  // 商品单价
                    .specifications(goodsProducts.get(0).getSpecifications())  // 规格信息
                    .picUrl(product.getString("imageUrl"))         // 商品图片
                    .comment(-1)                                   // 评论状态(-1表示未评论)
                    .addTime(now)                                  // 创建时间
                    .updateTime(now)                               // 更新时间
                    .build();
            orderGoodsList.add(goods);
        }

        return orderGoodsList;
    }

    /**
     * 解析订单时间
     * 将前端传来的时间字符串转换为LocalDateTime对象
     * 
     * @param orderData JSON格式的订单数据
     * @return LocalDateTime格式的时间
     * @throws Exception 当时间格式错误或信息缺失时抛出异常
     */
    private LocalDateTime parseOrderTime(JSONObject orderData) throws Exception {
        // 获取时间信息,确保不为空
        JSONObject time = Optional.ofNullable(orderData.getJSONObject("time"))
                .orElseThrow(() -> new IllegalArgumentException("时间信息不能为空"));

        // 解析时间字符串,格式如: "Wed Mar 20 2024 10:30:00 GMT+0800"
        String timeStr = time.getString("createTime");
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
        Date date = inputFormat.parse(timeStr.replaceAll("\\(.*\\)", "").trim());

        // 转换为LocalDateTime以便于数据库存储
        return date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
    }

    /**
     * 处理订单创建过程中的错误
     * 根据异常类型返回适当的错误信息
     * 
     * @param e 捕获的异常对象
     * @param errorMessage 错误信息字符串
     * @return 包含错误信息的响应对象
     */
    private Object handleOrderError(Exception e, String errorMessage) {
        String responseMsg;
        if (e instanceof DuplicateKeyException) {
            // 处理数据库唯一约束异常,细分不同的约束违反情况
            if (errorMessage.contains("duplicate") || errorMessage.contains("unique")) {
                responseMsg = "订单号重复，请不要重复提交";
            } else if (errorMessage.contains("cannot be null") || errorMessage.contains("not null")) {
                responseMsg = "必填字段不能为空";
            } else if (errorMessage.contains("foreign key") || errorMessage.contains("references")) {
                responseMsg = "关联数据不存在，请检查用户ID和公司ID";
            } else {
                responseMsg = "数据库约束错误";
            }
        } else {
            // 处理其他类型的异常
            responseMsg = "订单创建失败：" + e.getMessage();
            logger.error("订单创建失败：其他错误", e);
        }
        return ResponseUtil.fail(-1, responseMsg);
    }

    /**
     * 检查商品库存是否充足
     * @param orderGoodsList 订单商品列表
     * @return 库存是否充足
     */
    private boolean checkProductStock(List<LitemallOrderGoods> orderGoodsList) {
        // 收集所有商品ID
        List<Integer> goodsIds = orderGoodsList.stream()
                .map(LitemallOrderGoods::getGoodsId)
                .collect(Collectors.toList());
                
        // 一次性查询所有商品
        List<LitemallGoodsProduct> goodsProducts = goodsProductService.queryByGids(goodsIds);
        
        // 检查商品是否都存在
        if (goodsProducts.size() != goodsIds.size()) {
            return false;
        }
        
        // 创建商品ID到商品的映射
        Map<Integer, LitemallGoodsProduct> productMap = goodsProducts.stream()
                .collect(Collectors.toMap(
                    LitemallGoodsProduct::getGoodsId,
                    product -> product
                ));
        
        // 检查库存
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            LitemallGoodsProduct product = productMap.get(orderGoods.getGoodsId());
            if (product == null || product.getNumber() < orderGoods.getNumber()) {
                return false;
            }
        }
        
        return true;
    }

    /**
     * 从JSON数据解析订单基本信息
     * @param orderData JSON格式的订单数据
     * @return Order2对象
     * @throws IllegalArgumentException 当必要的订单信息缺失时
     */
    private Order2 parseOrderFromJson(JSONObject orderData) {
        if (orderData == null) {
            throw new IllegalArgumentException("订单数据不能为空");
        }

        try {
            // 获取必要的数据对象
            JSONObject contract = Optional.ofNullable(orderData.getJSONObject("contract"))
                    .orElseThrow(() -> new IllegalArgumentException("合同信息不能为空"));
            JSONObject payment = Optional.ofNullable(orderData.getJSONObject("payment"))
                    .orElseThrow(() -> new IllegalArgumentException("支付信息不能为空"));
            JSONObject companies = Optional.ofNullable(orderData.getJSONObject("companies"))
                    .orElseThrow(() -> new IllegalArgumentException("公司信息不能为空"));
            JSONObject supplier = Optional.ofNullable(companies.getJSONObject("supplier"))
                    .orElseThrow(() -> new IllegalArgumentException("供应商信息不能为空"));
            JSONObject buyer = Optional.ofNullable(companies.getJSONObject("buyer"))
                    .orElseThrow(() -> new IllegalArgumentException("买家信息不能为空"));

            // 获取订单基本信息
            String orderNo = contract.getString("content");
            Long userId = buyer.getJSONObject("details").getLong("userId");
            Long supplierId = supplier.getLong("id");
            Long buyerId = buyer.getLong("id");
            BigDecimal totalAmount = payment.getBigDecimal("totalAmount");
            BigDecimal payableAmount = payment.getBigDecimal("payableAmount");
            String paymentMethod = payment.getString("method");

            // 简单验证
            if (totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
                throw new IllegalArgumentException("总金额必须大于0");
            }

            LocalDateTime localDateTime = parseOrderTime(orderData);

            // 创建订单对象
            return Order2.builder()
                    .orderNo(orderNo)
                    .userId(userId)
                    .supplierCompanyId(supplierId)
                    .buyerCompanyId(buyerId)
                    .totalAmount(totalAmount)
                    .payableAmount(payableAmount)
                    .paymentMethod(paymentMethod)
                    .orderStatus(2)
                    .createTime(localDateTime)
                    .updateTime(localDateTime)
                    .build();
        } catch (Exception e) {
            throw new IllegalArgumentException("订单数据解析失败: " + e.getMessage());
        }
    }

    /**
     * 保存订单商品信息
     */
    private void saveOrderGoods(List<LitemallOrderGoods> orderGoodsList, Integer orderId) {
        if (orderGoodsList == null || orderGoodsList.isEmpty()) {
            throw new IllegalArgumentException("订单商品列表不能为空");
        }
        
        orderGoodsList.forEach(goods -> {
            goods.setOrderId(orderId);
            orderGoodsService.add(goods);
        });
    }

    /**
     * 更新商品库存
     */
    private void updateProductStock(List<LitemallOrderGoods> orderGoodsList) {
        if (orderGoodsList == null || orderGoodsList.isEmpty()) {
            return;
        }

        List<Integer> goodsIds = orderGoodsList.stream()
                .map(LitemallOrderGoods::getGoodsId)
                .collect(Collectors.toList());
                
        List<LitemallGoodsProduct> goodsProducts = goodsProductService.queryByGids(goodsIds);
        Map<Integer, LitemallGoodsProduct> productMap = goodsProducts.stream()
                .collect(Collectors.toMap(
                    LitemallGoodsProduct::getGoodsId,
                    product -> product
                ));
                
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            LitemallGoodsProduct product = productMap.get(orderGoods.getGoodsId());
            if (product != null) {
                int newStock = product.getNumber() - orderGoods.getNumber();
                if (newStock >= 0) {
                    product.setNumber(newStock);
                    goodsProductService.updateById(product);
                }
            }
        }
    }

    /**
     * 订单列表
     *
     * @param userId   用户ID
     * @param showType 显示类型，如果是0则是全部订单
     * @param page     分页页数
     * @param limit    分页大小
     * @param sort     排序字段
     * @param order    排序方式
     * @return 订单列表
     */
    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "0") Integer showType,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        return wxOrderService.list(userId, showType, page, limit, sort, order);
    }

    /**
     * 订单详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("detail")
    public Object detail(@LoginUser Integer userId, @NotNull Integer orderId) {
        return wxOrderService.detail(userId, orderId);
    }

    /**
     * 提交订单
     *
     * @param userId 用户ID
     * @param body   订单信息，{ cartId：xxx, addressId: xxx, couponId: xxx, message: xxx, grouponRulesId: xxx,  grouponLinkId: xxx}
     * @return 提交订单操作结果
     */
    @PostMapping("submit")
    public Object submit(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.submit(userId, body);
    }

    /**
     * 取消订单
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 取消订单操作结果
     */
    @PostMapping("cancel")
    public Object cancel(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.cancel(userId, body);
    }

    /**
     * 付款订单的预支付会话标识
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 支付订单ID
     */
    @PostMapping("prepay")
    public Object prepay(@LoginUser Integer userId, @RequestBody String body, HttpServletRequest request) {
        return wxOrderService.prepay(userId, body, request);
    }

    /**
     * 微信H5支付
     *
     * @param userId
     * @param body
     * @param request
     * @return
     */
    @PostMapping("h5pay")
    public Object h5pay(@LoginUser Integer userId, @RequestBody String body, HttpServletRequest request) {
        return wxOrderService.h5pay(userId, body, request);
    }

    /**
     * 微信付款成功或失败回调接口
     * <p>
     *  TODO
     *  注意，这里pay-notify是示例地址，建议开发者应该设立一个隐蔽的回调地址
     *
     * @param request  请求内容
     * @param response 响应内容
     * @return 操作结果
     */
    @PostMapping("pay-notify")
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) {
        return wxOrderService.payNotify(request, response);
    }

    /**
     * 订单申请退款
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @PostMapping("refund")
    public Object refund(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.refund(userId, body);
    }

    /**
     * 确认收货
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @PostMapping("confirm")
    public Object confirm(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.confirm(userId, body);
    }

    /**
     * 删除订单
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.delete(userId, body);
    }

    /**
     * 待评价订单商品信息
     *
     * @param userId 用户ID
     * @param ogid   订单商品ID
     * @return 待评价订单商品信息
     */
    @GetMapping("goods")
    public Object goods(@LoginUser Integer userId,
                        @NotNull Integer ogid) {
        return wxOrderService.goods(userId, ogid);
    }

    /**
     * 评价订单商品
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @PostMapping("comment")
    public Object comment(@LoginUser Integer userId, @RequestBody String body) {
        return wxOrderService.comment(userId, body);
    }

    @PostMapping("/generateContract")
    public Object generateContract(@RequestBody Map<String, Object> orderDTO) {
        ObjectMapper mapper = new ObjectMapper();
        LitemallCompanyInfo buyerCompany = mapper.convertValue(orderDTO.get("buyerCompany"), LitemallCompanyInfo.class);
        LitemallCompanyInfo supplierCompany = mapper.convertValue(orderDTO.get("supplierCompany"), LitemallCompanyInfo.class);
        OrderDTO encodedData = mapper.convertValue(orderDTO.get("encodedData"), OrderDTO.class);

        if (encodedData == null || encodedData.getProducts() == null || encodedData.getAddress() == null) {
            return ResponseUtil.badArgument();
        }
        try {
            // 读取HTML模板
            String html = readHtmlTemplate("templates/good.html");

            // 替换模板中的动态内容
            Map<String, String> replacements = new HashMap<>();
            // 设置基本信息
            String orderId = String.format("%s%06d", new SimpleDateFormat("yyyyMMdd").format(new Date()),
                    (int) (Math.random() * 999999));
            replacements.put("采购编号", orderId);
            replacements.put("采购日期", new SimpleDateFormat("yyyy/MM/dd").format(new Date()));

            // 设置供方信息
            replacements.put("供方公司", supplierCompany.getName());
            replacements.put("供方地址", supplierCompany.getAddress());
            replacements.put("供方联系人", "");
            replacements.put("供方联系电话", supplierCompany.getPhone());

            // 设置需方(买方)信息
            replacements.put("需方公司", buyerCompany.getName());
            replacements.put("地址", encodedData.getAddress().getProvince() + "-" + encodedData.getAddress().getCity() + encodedData.getAddress().getCounty() + encodedData.getAddress().getAddressDetail());
            replacements.put("联系人", encodedData.getAddress().getName());
            replacements.put("联系电话", encodedData.getAddress().getTel());

            // 生成商品表格HTML
            StringBuilder productsHtml = new StringBuilder();
            BigDecimal total = BigDecimal.ZERO;
            int index = 1;

            for (ProductItem item : encodedData.getProducts()) {
                BigDecimal itemTotal = item.getGood().getGoodsProduct().getPrice().multiply(new BigDecimal(item.getQuantity()));
                productsHtml.append("<tr>")
                        .append("<td>").append(index++).append("</td>")
                        .append("<td>").append(item.getGood().getGoods().getName()).append("</td>")
                        .append("<td>").append(item.getGood().getGoodsProduct().getSpecifications()).append("</td>")
                        .append("<td>件</td>")
                        .append("<td>").append(item.getQuantity()).append("</td>")
                        .append("<td>").append(item.getGood().getGoodsProduct().getPrice().setScale(2, RoundingMode.HALF_UP)).append("</td>")
                        .append("<td>").append(itemTotal.setScale(2, RoundingMode.HALF_UP)).append("</td>")
                        .append("<td>").append(item.getGood().getGoods().getId()).append("</td>")
                        .append("<td>").append(item.getGood().getGoods().getBrief() == null ? "" : item.getGood().getGoods().getBrief()).append("</td>")
                        .append("</tr>");
                total = total.add(itemTotal);
            }

            replacements.put("PRODUCTS_TABLE", productsHtml.toString());
            replacements.put("合计金额", total.setScale(2, RoundingMode.HALF_UP).toString());
            replacements.put("金额大写", convertToChineseMoney(total));

            // 替换模板中的所有标记
            for (Map.Entry<String, String> entry : replacements.entrySet()) {
                html = html.replace("${" + entry.getKey() + "}", entry.getValue());
            }
            // 生成PDF文件名
            String pdfFileName = "contract_" + orderId + ".pdf";

            // 生成PDF
            generatePdf(html, pdfFileName);
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("html", html);
            return ResponseUtil.ok(map);

        } catch (Exception e) {
            logger.error("生成合同异常", e);
            return ResponseUtil.fail();
        }
    }

    // 添加辅助方法
    private String readHtmlTemplate(String path) {
        try {
            ClassLoader classLoader = getClass().getClassLoader();
            try (InputStream inputStream = classLoader.getResourceAsStream(path)) {
                if (inputStream == null) {
                    throw new RuntimeException("找不到模板文件: " + path);
                }
                return inputStreamToString(inputStream);
            }
        } catch (IOException e) {
            logger.error("读取合同模板异常", e);
            throw new RuntimeException("无法读取合同模板: " + e.getMessage(), e);
        }
    }

    private String inputStreamToString(InputStream inputStream) throws IOException {
        StringBuilder textBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                textBuilder.append(line).append("\n");
            }
        }
        return textBuilder.toString();
    }

    private String convertToChineseMoney(BigDecimal number) {
        // 确保金额精确到分
        number = number.setScale(2, RoundingMode.HALF_UP);

        // 处理零元的情况
        if (number.compareTo(BigDecimal.ZERO) == 0) {
            return "零元整";
        }

        // 数字对应的中文
        String[] numArray = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        // 整数部分的单位
        String[] intUnits = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
        // 小数部分的单位
        String[] decUnits = {"角", "分"};

        // 分离整数和小数部分
        String numStr = number.toString();
        String[] parts = numStr.split("\\.");
        String intPart = parts[0];
        String decPart = parts.length > 1 ? parts[1] : "00";

        StringBuilder result = new StringBuilder();

        // 处理整数部分
        boolean isZero = true; // 标记是否全部为零
        for (int i = 0; i < intPart.length(); i++) {
            int digit = intPart.charAt(i) - '0';
            int position = intPart.length() - i - 1;

            if (digit != 0) {
                isZero = false;
                result.append(numArray[digit]);
                result.append(intUnits[position]);
            } else {
                // 处理连续的零
                if (!isZero && i < intPart.length() - 1 && intPart.charAt(i + 1) != '0') {
                    result.append(numArray[0]);
                }
                // 处理万位和亿位
                if (position == 4 || position == 8) {
                    boolean hasDigitAfter = false;
                    for (int j = i + 1; j < intPart.length(); j++) {
                        if (intPart.charAt(j) != '0') {
                            hasDigitAfter = true;
                            break;
                        }
                    }
                    if (hasDigitAfter) {
                        result.append(intUnits[position]);
                    }
                }
            }
        }

        if (!isZero) {
            result.append("元");
        }

        // 处理小数部分
        boolean hasDecimal = false;
        for (int i = 0; i < Math.min(decPart.length(), 2); i++) {
            int digit = decPart.charAt(i) - '0';
            if (digit != 0) {
                hasDecimal = true;
                result.append(numArray[digit]).append(decUnits[i]);
            }
        }

        // 如果没有小数部分，添加"整"
        if (!hasDecimal) {
            result.append("整");
        }

        return result.toString();
    }

    private void generatePdf(String html, String outputPath) throws IOException {
        // 确保目录存在
        File directory = new File(pdfSavePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 生成PDF文件
        String pdfPath = pdfSavePath + File.separator + outputPath;
        try (FileOutputStream outputStream = new FileOutputStream(pdfPath)) {
            PdfWriter writer = new PdfWriter(outputStream);

            // 设置字体
            ConverterProperties properties = new ConverterProperties();
            DefaultFontProvider fontProvider = new DefaultFontProvider();
            fontProvider.addSystemFonts(); // 添加系统字体
            properties.setFontProvider(fontProvider);

            // 转换HTML为PDF
            HtmlConverter.convertToPdf(html, writer, properties);
        }
    }

    //已售
    @GetMapping("/sold/{supplierCompanyId}")
    public Object sold(String keyword, @PathVariable Integer supplierCompanyId) {
        try {
            // 参数校验
            if (supplierCompanyId == null || supplierCompanyId <= 0) {
                return ResponseUtil.badArgument();
            }

            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("supplierCompanyId", supplierCompanyId);
            params.put("keyword", StringUtils.isEmpty(keyword) ? "" : keyword);
            
            // 调用订单商品服务查询已售商品列表
            List<Map<String, Object>> soldItems = wxOrderService.querySupplierCompanyItems(params);
            
            // 处理返回数据
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Map<String, Object> item : soldItems) {
                Map<String, Object> resultItem = new HashMap<>();
                resultItem.put("image", item.get("image"));
                resultItem.put("title", item.get("title"));
                resultItem.put("description", item.get("description"));
                resultItem.put("price", item.get("price"));
                resultItem.put("soldTime", item.get("soldTime"));
                resultItem.put("status", item.get("status"));
                resultList.add(resultItem);
            }
            return ResponseUtil.ok(resultList);
        } catch (Exception e) {
            logger.error("查询已售商品列表失败", e);
            return ResponseUtil.fail(-1, "查询失败：" + e.getMessage());
        }
    }
//    public Object purchased(String keyword, @PathVariable Integer buyerCompanyId) {
//        try {
//            // 参数校验
//            if (buyerCompanyId == null || buyerCompanyId <= 0) {
//                return ResponseUtil.badArgument();
//            }
//
//            // 构建查询参数
//            Map<String, Object> params = new HashMap<>();
//            params.put("buyerCompanyId", buyerCompanyId);
//            params.put("keyword", StringUtils.isEmpty(keyword) ? "" : keyword);
//
//            List<Map<String, Object>> soldItems = wxOrderService.queryPurchasedItems(params);
//
//            // 处理返回数据
//            List<Map<String, Object>> resultList = new ArrayList<>();
//            for (Map<String, Object> item : soldItems) {
//                Map<String, Object> resultItem = new HashMap<>();
//                resultItem.put("image", item.get("image"));
//                resultItem.put("title", item.get("title"));
//                resultItem.put("description", item.get("description"));
//                resultItem.put("price", item.get("price"));
//                resultItem.put("soldTime", item.get("soldTime"));
//                resultItem.put("status", item.get("status"));
//                resultList.add(resultItem);
//            }
//
//            return ResponseUtil.ok(resultList);
//        } catch (Exception e) {
//            logger.error("查询已售商品列表失败", e);
//            return ResponseUtil.fail(-1, "查询失败：" + e.getMessage());
//        }
//    }


    //已买
    @GetMapping("/purchased/{userId}")
    public Object purchased(String keyword, @PathVariable Integer userId) {
        try {
            // 参数校验
            if (userId == null || userId <= 0) {
                return ResponseUtil.badArgument();
            }
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("keyword", StringUtils.isEmpty(keyword) ? "" : keyword);

            List<Map<String, Object>> soldItems = wxOrderService.querySoldItems(params);

            // 处理返回数据
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Map<String, Object> item : soldItems) {
                Map<String, Object> resultItem = new HashMap<>();
                resultItem.put("image", item.get("image"));
                resultItem.put("title", item.get("title"));
                resultItem.put("description", item.get("description"));
                resultItem.put("price", item.get("price"));
                resultItem.put("soldTime", item.get("soldTime"));
                resultItem.put("status", item.get("status"));
                resultList.add(resultItem);
            }

            return ResponseUtil.ok(resultList);
        } catch (Exception e) {
            logger.error("查询已售商品列表失败", e);
            return ResponseUtil.fail(-1, "查询失败：" + e.getMessage());
        }
    }
}